/**
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 *
 * @data:2017年10月10日
 * @author:MaShibo
 */
package com.wttech.dzzf.process.service.user;

import com.wtkj.vo.dzzf.base.kfwd.CardInfo;
import com.wtkj.vo.dzzf.base.kfwd.FundAccount;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.model.user.User;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;


/**
 * 用户相关信息编码
 *
 * @author MaShibo
 * @date 2017年10月10日
 */
@Service
public class UserInfosCreatorService {


    private static final Logger LOGGER = LoggerFactory.getLogger(UserInfosCreatorService.class);

    private static final Logger ERRORINFO = LoggerFactory.getLogger("ErrorInfo");

    /**
     * 默认处理数量
     */
    private static final int DEFAULT_PROCESS_NUM = 10000;

    @Resource
    private TransferUserInfoDao transferUserInfoDao;

    @Resource
    private ThreadPoolTaskExecutor executor;


    @Resource
    private UserDetailInfosCreatorService userDetailInfosCreatorService;


    public UserInfosCreatorService() {
    }

    @Autowired
    public UserInfosCreatorService(TransferUserInfoDao transferUserInfoDao) {
        this.transferUserInfoDao = transferUserInfoDao;
    }

    /**
     * 迁移数据后处理
     */
    private void processNormalDataV2() {
        /*
      待处理的总数量
     */
        int total = transferUserInfoDao.queryAccountNumV2(true);
        LOGGER.info("共{}条正常数据待处理", total);
        int count = (int) Math.ceil((double) total / DEFAULT_PROCESS_NUM);
        LOGGER.info("共需要处理{}次", count);


        for (int i = 0; i < count; i++) {
            int num = i + 1;
            LOGGER.info("第{}次，开始执行...", num);
            int startRow = (num - 1) * DEFAULT_PROCESS_NUM + 1;
            int endRow = num * DEFAULT_PROCESS_NUM;
            List<Future<Void>> futures = new ArrayList<>();
            List<FundAccount> fundAccounts = transferUserInfoDao.queryNormalAccountInfosV2(startRow, endRow);
            fundAccounts.forEach(fundAccount -> futures.add(executor.submit(() -> {
                processSingleData(fundAccount);
                return null;
            })));
            userDetailInfosCreatorService.getFutureResult(futures);
            LOGGER.info("第{}次，结束执行...", num);
        }
        LOGGER.info("执行完毕");
        executor.shutdown();
    }

    public void processCardAboutInfos(String cardId){
        int count = transferUserInfoDao.queryCardUploadInfoById(cardId);
        if (count >= 1){
            return;
        }
        String cardNo = StringUtils.substring(cardId, 4);
        FundAccount fundAccount = transferUserInfoDao.queryFundAccountByEcardNo(cardNo);
        if (fundAccount == null){
            LOGGER.error("卡片【{}】，没有对应的资金账户信息", cardId);
            return;
        }
        //构建客户信息
        User user = userDetailInfosCreatorService.buildUserInfo(fundAccount);
        CardInfo  cardInfo = transferUserInfoDao.queryCardInfoByNo(cardNo);
        userDetailInfosCreatorService.dealWithCardAboutInfos(user, cardInfo);
    }


    private void processSingleData(FundAccount fundAccount) {

        try {
            //构建客户信息
            User user = userDetailInfosCreatorService.buildUserInfo(fundAccount);

            // 查询卡片信息
            List<CardInfo> cardInfos = transferUserInfoDao.queryCardInfosByFundAccount(fundAccount.getFundAccountId());
            if (cardInfos.isEmpty()) {
                //无卡片信息的客户信息不创建客户信息
                return;
            }

            //遍历处理每条卡片信息
            cardInfos.forEach(cardInfo -> userDetailInfosCreatorService.dealWithCard(user, cardInfo));

            //创建客户信息
            userDetailInfosCreatorService.createUserInfo(user);

        } catch (Exception e) {
            LOGGER.debug(e.getMessage(), e);
            ERRORINFO.error(e.getMessage());
        }
    }



    public static void main(String[] args) {
        @SuppressWarnings({"resource", "unused"})
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserInfosCreatorService service = context.getBean(UserInfosCreatorService.class);
        service.processNormalDataV2();
    }

}
